package com.slg.android.manyanime.fragment;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.slg.android.manyanime.ChannelActivity;
import com.slg.android.manyanime.R;
import com.slg.android.manyanime.adapter.AnimeListAdapter;
import com.slg.android.manyanime.bean.Channel;
import com.slg.android.manyanime.utils.ApiUtils;
import com.slg.android.manyanime.utils.NetUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class AnimeListFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2<ListView>, AdapterView.OnItemClickListener {
    @ViewInject(R.id.common_loading)
    private RelativeLayout loading;
    @ViewInject(R.id.common_loading_image)
    private ImageView loadingImage;
    @ViewInject(R.id.anime_list_pullToRefreshListView)
    private PullToRefreshListView pullToRefreshListView;
    private android.view.animation.Animation loadingAnimation;
    private ListView listView;
    private String json;
    private String lastId = "";
    private boolean haveMore;
    private List<Channel> data;
    private final String SHARED_JSON = "AnimeListJsonData";
    private SharedPreferences sharedPreferences;
    private HttpUtils utils;
    private AnimeListAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FragmentActivity activity = getActivity();
        sharedPreferences = activity.getSharedPreferences("JSON", activity.MODE_PRIVATE);
        json = sharedPreferences.getString(SHARED_JSON, null);
        data = new ArrayList<>();
        utils = new HttpUtils();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_anime_list, container, false);
        ViewUtils.inject(this, view);
        listView = pullToRefreshListView.getRefreshableView();
        listView.setOnItemClickListener(this);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        if (json == null) {
            if (NetUtil.isConnectInternet(getActivity())) {
                loading.setVisibility(View.VISIBLE);
                loadingAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_common_rotate);
                loadingImage.startAnimation(loadingAnimation);
                load(true, false);
            }
        } else {
            parseData(false);
            adapter = new AnimeListAdapter(getActivity(), data);
            listView.setAdapter(adapter);
        }
        return view;
    }

    private void parseData(boolean loadMore) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            haveMore = jsonObject.getBoolean("have_next");
            lastId = jsonObject.getString("last_id");
            JSONArray topic = jsonObject.getJSONArray("topic");
            if (loadMore) {
                data.addAll(Channel.parseData(topic));
            } else {
                if (data != null) {
                    data.clear();
                }
                data = Channel.parseData(topic);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        if (refreshView.isRefreshing()) {
            load(false, false);
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        if (refreshView.isRefreshing()) {
            if (!haveMore) {
                Toast.makeText(getActivity(), "没有更多内容了", Toast.LENGTH_SHORT).show();
                pullToRefreshListView.onRefreshComplete();
            } else {
                load(false, true);
            }
        }
    }

    private void load(final boolean showLoading, final boolean loadMore) {
        if (NetUtil.isConnectInternet(getActivity())) {
            utils.send(HttpRequest.HttpMethod.GET,
                    ApiUtils.ANIMATION_CHANNEL + lastId
                    , new RequestCallBack<String>() {
                        @Override
                        public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                            json = objectResponseInfo.result;
                            if (showLoading) {
                                loadingAnimation.cancel();
                                loading.setVisibility(View.GONE);
                            }
                            if (!loadMore) {
                                SharedPreferences.Editor edit = sharedPreferences.edit();
                                edit.putString(SHARED_JSON, json);
                                edit.commit();
                            }
                            parseData(loadMore);
                            if (loadMore) {
                                adapter.notifyDataSetChanged();
                                pullToRefreshListView.onRefreshComplete();
                            } else {
                                adapter = new AnimeListAdapter(getActivity(), data);
                                listView.setAdapter(adapter);
                                pullToRefreshListView.onRefreshComplete();
                            }
                        }

                        @Override
                        public void onFailure(HttpException e, String s) {
                            if (showLoading) {
                                loadingAnimation.cancel();
                                loading.setVisibility(View.GONE);
                            }
                            Toast.makeText(getActivity(), R.string.no_network, Toast.LENGTH_SHORT)
                                    .show();
                            Log.e("网络异常", "s", e);
                            if (loadMore) {
                                pullToRefreshListView.onRefreshComplete();
                            }
                        }
                    });
        } else {
            Toast.makeText(getActivity(), R.string.no_network, Toast.LENGTH_SHORT)
                    .show();
            pullToRefreshListView.onRefreshComplete();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int count = listView.getHeaderViewsCount();
        Channel channel = data.get(position - count);
        Intent intent = new Intent(getActivity(), ChannelActivity.class);
        intent.putExtra("id", channel.getId());
        startActivity(intent);
    }
}
